package com.api.syh56.shengyunhui.handler;

import com.api.syh56.shengyunhui.common.BaseUserInfo;
import com.auth0.jwt.interfaces.DecodedJWT;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;
import com.api.syh56.shengyunhui.util.JWTUtils;

@Slf4j
public class JWTHandler implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler){
        String requestURI = request.getRequestURI();
        //获得请求头里的TOKEN数据
        String token = request.getHeader("token");

        log.info("requstURI:"+requestURI);
        log.info("token:"+token);

        //根据token解析数据，因为配置了全局异常处理中心，如果有异常会在全局异常中心处理异常
        DecodedJWT tokenInfo = JWTUtils.getTokenInfo(token);
        //获得用户信息
        String id = tokenInfo.getClaim("id").asString();
        String name = tokenInfo.getClaim("name").asString();
        //存储用户信息到ThreadLocal中
        BaseUserInfo.set("id",id);
        BaseUserInfo.set("name",name);

        log.info("id:"+id);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

        System.out.println(response.getHeader("token"));
    }
}


